#!/bin/bash
if [ "$1" = "" ];then
    echo "no input argument";exit 1;
fi

while getopts h:l:i:c:f: arg 
do 
    case $arg in 
        h) 
	home=$OPTARG
        ;; 
        l) 
        logfile=$OPTARG
        ;; 
        i) 
        instance=$OPTARG
        ;; 
        c) 
       	codefile=$OPTARG
        ;; 
        f) 
       	   force=$OPTARG
        ;; 
        \?)
        echo "unknown argument" ;
        exit 1;
        ;; 
    esac    
done 

if [ -z $instance ];then
    echo "no input argument -i";exit 1;
fi
if [ -z $home ];then
    echo "no input argument -h";exit 1;
fi
if [ -z $codefile ];then
    echo "no input argument -c,specify recode file";exit 1;
fi
if [ -z $logfile ];then
    echo "no input argument -l,specify log file";exit 1;
fi
if [ ! -z $force ];then
    force='--force'
    echo "--force"
fi

echo '' > $logfile

for index in {1..30}
do
    echo '' > $logfile
    $home/lich/admin/cluster.py health scan >> $logfile 2>&1;
    echo $? > $codefile 
    
    HEALTH_RESULT=`cat $logfile |grep 'chunk need recovery\|chunk recovery lost\|chunk recovery fail'|awk -F: '{print $2}'`
    ISSUCC=1
    for x in $HEALTH_RESULT
    do
        if [ $x != 0 ];then
            ISSUCC=0
        fi
    done 
    if [ $ISSUCC == 1 ];then
        break
    fi
done
echo $ISSUCC

if [ $ISSUCC == 1 ];then
    echo "$home/lich/admin/node.py --disk_del  $instance $force>> $logfile 2>&1;echo $? > $codefile"
    $home/lich/admin/node.py --disk_del  $instance $force>> $logfile 2>&1;echo $? > $codefile
    droprecode=`cat $codefile`;
    if [ "$droprecode" != 0 ];then
        tail -n 100 $logfile |grep "disk_num not in service"
        result=$?
        if [ "$result" = 0 ];then
            echo $result > $codefile
            exit 0 
        fi
        tail -n 100 $logfile |grep "No space left on device\|try use --force\|Read-only file system"
        result=$?;
        if [ "$result" = 0 ];then
            echo "trying to use force disk_del"
            $home/lich/admin/node.py --disk_del  $instance --force>> $logfile 2>&1;echo $? > $codefile
            forcerecode=$?
            if [ "$forcerecode" != 0 ];then
                echo -e "\033[1;31m --force dropinstance  fail\033[0m"
                exit $forcerecode
            fi  
        else
            echo -e "\033[1;31m dropinstance  fail\033[0m"
            exit $result
        fi  
    fi  
else
    echo -e "\033[1;31m dropinstance  fail\033[0m"
    echo '9005' > $CODEFILE
    exit 1
fi
